//logs.js
let that = null;
import store from "../../utils/factory";
import {
    getShopCarList,
    shopCarAdd,
    delShopCar,
    updateShopCar,
    getConfig
} from "../../utils/config";
import {
    accAdd,
    accSub,
    accMul,
} from "../../utils/util"

Component({
    pageLifetimes: {
        show() {
            if (typeof this.getTabBar === "function" && this.getTabBar()) {
                this.getTabBar().setData({
                    selected: 2
                });
                this.getTabBar().setData({
                    count: 0
                });
                if (store.get("userInfo")) {
                    this.getConfig()
                    this.getTotal();
                } else {
                    wx.navigateTo({
                        url: "../autoLogin/autoLogin"
                    });
                }
            }
        },
        hide() {
            this.getTabBar().setData({
                count: 0
            });
        }
    },
    observers: {
        'total': function (total) { //  'params'是要监听的字段，（params）是已更新变化后的数
            if ((total - this.data.express) > store.get("expressThreshold")) {
                this.setData({
                    haveExpress: false,
                    money: (total - 0).toFixed(2)
                })
            } else {
                this.setData({
                    haveExpress: true,
                    money: total
                })
            }
        }
    },
    data: {
        shopCarList: [],
        total: 0,
        money: 0,
        express: 0,
        totalNum: 0,
        haveExpress: true,
        allCheckStatus: false
    }, // 私有数据，可用于模板渲染
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached: function () {
        that = this;
    }, // 此处attached的声明会被lifetimes字段中的声明覆盖
    ready: function () {},
    methods: {
        onShareAppMessage() {
            return {
                title: "热度零食铺",
                path: '/pages/index/index'
            }
        },
        getConfig() {
            getConfig()
                .then(res => {
                    console.log(res.data);
                    let req = res.data;
                    if (req) {
                        store.set("express", req.express);
                        store.set("wholeSale", req.wholeSale);
                        store.set("expressThreshold", req.expressThreshold)
                    }
                })
                .catch(err => {});
        },
        chatFn() {
            wx.switchTab({
                url: "../classify/classify"
            });
        },
        getTotal() {
            getShopCarList().then(res => {
                let req = res.data;
                this.getTabBar().setData({
                    count: req.quantity || 0
                });
                let unSelectList = store.get("unSelectList") || [];
                let shopCarList = req.items || [];
                let total = 0;
                let totalNum = 0;
                let b = -1;
                total = accAdd(req.total, 0);
                totalNum = req.quantity;
                if (shopCarList.length > 0) {
                    if (unSelectList.length == 0) {
                        shopCarList.map(item => {
                            item.select = "selected";
                        });
                    } else {
                        shopCarList.map(item => {
                            let a = unSelectList.find(value => {
                                return value.id == item.id;
                            });
                            if (!a) {
                                item.select = "selected";
                            } else {
                                item.select = "unselect";
                                b = 1;
                                totalNum = accSub(totalNum, item.quantity);
                                total = accSub(total, accMul(item.marketPrice, item.quantity));
                            }
                        });
                    }
                    console.log("b", b);
                }
                this.setData({
                    shopCarList: shopCarList,
                    total: total.toFixed(2),
                    totalNum: totalNum,
                    express: store.get("express") || 0,
                    allCheckStatus: b == -1 ? true : false,
                    pageShow: true
                });
                console.log(typeof this.data.total)
            });
        },
        goDetail(e) {
            console.log(e);
            const id = e.currentTarget.dataset.id;
            let type = e.currentTarget.dataset.type;
            console.log(type);
            if (!type) {
                wx.navigateTo({
                    url: `../logs/logs?id=${id}`
                });
            } else {
                return false;
            }
            // console.log(id)
        },
        // 选中
        addItem(e) {
            let index = e.currentTarget.dataset.index;
            let shopCarList = this.data.shopCarList;
            let unSelectList = store.get("unSelectList") || [];
            if (unSelectList.length > 0) {
                let b = unSelectList.findIndex(value => {
                    return value.id == shopCarList[index].id;
                });
                if (b != -1) {
                    unSelectList.splice(b, 1);
                    store.set("unSelectList", unSelectList);
                }
            }
            shopCarList[index].select = "selected";
            let _index = shopCarList.find(value => {
                return value.select == "unselect";
            });
            let a = accAdd(this.data.total,
                accMul(shopCarList[index].quantity, shopCarList[index].marketPrice))
            this.setData({
                shopCarList: shopCarList,
                total: a.toFixed(2),
                totalNum: accAdd(this.data.totalNum, shopCarList[index].quantity),
                allCheckStatus: _index ? false : true
            });
        },
        // 不选中
        reduceItem(e) {
            let index = e.currentTarget.dataset.index;
            let shopCarList = this.data.shopCarList;
            let unSelectList = store.get("unSelectList") || [];
            shopCarList[index].select = "unselect";
            unSelectList.push({
                id: shopCarList[index].id
            });
            store.set("unSelectList", unSelectList);
            let a = accAdd(this.data.total,
                -(accMul(shopCarList[index].quantity, shopCarList[index].marketPrice)))
            this.setData({
                total: a.toFixed(2),
                totalNum: accAdd(this.data.totalNum, -shopCarList[index].quantity),
                shopCarList: shopCarList,
                allCheckStatus: false
            });
            store.set("shopCarList", shopCarList);
        },
        // 全选
        allCheck() {
            let shopCarList = this.data.shopCarList;
            let unSelectList = [];
            let total = 0;
            let totalNum = 0;
            if (this.data.allCheckStatus) {
                shopCarList.map(item => {
                    item.select = "unselect";
                    unSelectList.push({
                        id: item.id
                    });
                });
                store.set("unSelectList", unSelectList);
                this.setData({
                    total: total.toFixed(2),
                    totalNum: totalNum,
                    shopCarList: shopCarList,
                    allCheckStatus: false
                });
            } else {
                shopCarList.map(item => {
                    item.select = "selected";
                    totalNum = accAdd(totalNum, item.quantity);
                    total = accAdd(total, accMul(item.marketPrice, item.quantity));
                });
                store.remove("unSelectList");
                this.setData({
                    shopCarList: shopCarList,
                    totalNum: totalNum,
                    total: total.toFixed(2),
                    allCheckStatus: true
                });
            }
        },
        //减
        bindMinus(e) {
            let index = e.currentTarget.dataset.index;
            let shopCarList = this.data.shopCarList;
            if (shopCarList[index].quantity == 1) {
                wx.showModal({
                    title: "温馨提示",
                    content: "确认删除该商品么?",
                    success: function (res) {
                        if (!res.cancel) {
                            delShopCar([shopCarList[index].id]).then(res => {
                                that.getTotal();
                            });
                        }
                    }
                });
            } else {
                shopCarList[index].quantity = accAdd(shopCarList[index].quantity, -1);
                shopCarAdd({
                    category: shopCarList[index].id,
                    quantity: -1
                }).then(res => {
                    let req = res.data;
                    this.getTabBar().setData({
                        count: req.quantity
                    });
                    if (shopCarList[index].select == "unselect") {
                        this.setData({
                            shopCarList: shopCarList
                        });
                    } else {
                        this.setData({
                            totalNum: accAdd(this.data.totalNum, -1),
                            total: accAdd(this.data.total, -shopCarList[index].marketPrice).toFixed(2),
                            shopCarList: shopCarList
                        });
                    }
                });
            }
        },
        bindInput() {},
        // 输入
        bindManual(e) {
            let index = e.currentTarget.dataset.index;
            let shopCarList = this.data.shopCarList;
            let total = this.data.total;
            let totalNum = this.data.totalNum;
            if (e.detail.value == 0) {
                wx.showToast({
                    title: "输入的商品数量不能为0",
                    icon: "none"
                });
                // 总数减去老的数量
                totalNum = accAdd(totalNum, -shopCarList[index].quantity);
                total =
                    accAdd(total, -(accMul(shopCarList[index].quantity, shopCarList[index].marketPrice)));
                // 总数加上新的数量
                shopCarList[index].quantity = 1;
                totalNum = accAdd(totalNum, 1);
                total = accAdd(total, shopCarList[index].marketPrice);
                this.updateShopCar(
                    shopCarList[index].id,
                    1,
                    shopCarList,
                    totalNum,
                    total
                );
                return false;
            }
            // 总数减去老的数量
            totalNum = accAdd(totalNum, -shopCarList[index].quantity);
            total =
                accAdd(total, -(accMul(shopCarList[index].quantity, shopCarList[index].marketPrice)));
            // 总数加上新的数量
            shopCarList[index].quantity = e.detail.value;
            totalNum = accAdd(totalNum, e.detail.value);
            total =
                accAdd(total, accMul(shopCarList[index].quantity, shopCarList[index].marketPrice));
            this.updateShopCar(
                shopCarList[index].id,
                e.detail.value,
                shopCarList,
                totalNum,
                total
            );
        },
        updateShopCar(id, quantity, shopCarList, totalNum, total) {
            updateShopCar({
                category: id,
                quantity: quantity
            }).then(res => {
                that.setData({
                    totalNum: totalNum,
                    total: total.toFixed(2),
                    shopCarList: shopCarList
                });
            });
        },
        //加
        bindPlus(e) {
            let index = e.currentTarget.dataset.index;
            let shopCarList = this.data.shopCarList;
            if (!shopCarList[index]) {
                wx.showToast({
                    title: "该商品不存在",
                    icon: "none"
                });
                return false;
            }
            if (shopCarList[index].saleOut) {
                wx.showToast({
                    title: "该商品已经售罄",
                    icon: "none"
                });
                return false;
            }
            shopCarList[index].quantity = accAdd(shopCarList[index].quantity, 1);
            shopCarAdd({
                category: shopCarList[index].id,
                quantity: 1
            }).then(res => {
                let req = res.data;
                this.getTabBar().setData({
                    count: req.quantity
                });
                if (shopCarList[index].select == "unselect") {
                    this.setData({
                        shopCarList: shopCarList
                    });
                } else {
                    this.setData({
                        totalNum: accAdd(this.data.totalNum, 1),
                        total: accAdd(this.data.total, shopCarList[index].marketPrice).toFixed(2),
                        shopCarList: shopCarList
                    });
                }
            });
        },
        submitOrder() {
            if (this.data.totalNum == 0) {
                wx.showToast({
                    title: "商品数量为空不能提交",
                    icon: "none"
                });
                return false;
            }
            let selectShopCarList = [];
            this.data.shopCarList.map(item => {
                if (item.select == "selected") {
                    selectShopCarList.push(item);
                }
            });
            let submitOrderDetail = {
                shopCarList: selectShopCarList,
                total: this.data.money,
                haveExpress: this.data.haveExpress
            };
            store.set("submitOrderDetail", submitOrderDetail);
            wx.navigateTo({
                url: `../submitOrder/submitOrder`
            });
        }
    }
});